<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="试题管理" name="questions_list">
        <el-form :model="query" :inline="true">
          <el-form-item>
            <el-upload
              :headers="headers"
              class="upload-demo"
              :action="uploadExcelAction"
              :with-credentials="true"
              :on-success="uploadExcelSuccess"
              :before-upload="beforeUploadExcel"
              :show-file-list="false">
              <el-button icon="el-icon-upload" v-if="hasPermission(['system:question:import'])" size="small" type="primary">试题导入</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button size="small" icon="el-icon-download" @click="downTemplate" type="success">下载模板</el-button>
          </el-form-item>

          <education-search
            @click="searchQuestion"
            :school_type_list="schoolTypeList"
            :grade_type_list="gradeTypeList"
            permission="system:question:list">
          </education-search>
        </el-form>
        <el-table
          v-loading="tableLoading"
          border
          :data="questionsList"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>

          <el-table-column
            prop="content"
            align="center"
            :show-overflow-tooltip="true"
            label="试题内容"
            min-width="150">
            <template slot-scope="scope">
              <div v-html="scope.row.content"></div>
            </template>
          </el-table-column>

          <el-table-column
            v-if="showTableHeader"
            prop="subject_name"
            align="center"
            width="100"
            label="科目">
          </el-table-column>

          <el-table-column
            v-if="showTableHeader"
            prop="grade_type"
            align="center"
            sortable
            label="阶段"
            width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.school_type === 1" size="small">小学</el-tag>
              <el-tag v-else-if="scope.row.school_type === 2" size="small">初中</el-tag>
              <el-tag v-else-if="scope.row.school_type === 3" size="small">高中</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            v-if="showTableHeader"
            width="150"
            align="center"
            sortable
            prop="grade_info_name"
            label="年级">
            <template slot-scope="scope">
              <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="questions_type_name"
            width="100"
            align="center"
            label="类型">
            <template slot-scope="scope">
              <el-tag size="small" >{{scope.row.question_type | getQuestionTypeName}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="create_date"
            align="center"
            width="120"
            sortable
            :formatter="formatterCreateDate"
            label="创建时间">
          </el-table-column>

          <el-table-column
            header-align="center"
            align="center"
            width="200"
            label="操作">
            <template slot-scope="scope">

              <el-button
                size="small"
                icon="el-icon-view"
                v-if="hasPermission(['system:question:update'])"
                @click="lookQuestion(scope.row)"
                type="text">预览</el-button>

              <el-button
                size="small"
                icon="el-icon-edit"
                v-if="hasPermission(['system:question:update'])"
                @click="updateQuestions(scope.row)"
                type="text">修改</el-button>

              <el-button
                size="small"
                icon="el-icon-delete"
                v-if="hasPermission(['system:question:deleteById'])"
                @click="deleteById(scope.row)"
                type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

      </el-tab-pane>
      <el-tab-pane v-if="hasPermission(['system:question:save', 'system:question:update'])"  :label="labelName" name="questions_form">
         <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
          <el-col :span="12">
            <el-form-item label="阶段:" prop="school_type">
              <el-select
                clearable filterable
                @change="changeSchoolType"
                v-model="form.school_type"
               placeholder="请选择阶段">
                <el-option
                  v-for="item in schoolTypeList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="类型:"  prop="question_type">
              <el-select clearable filterable @change="changeQuestionType" v-model="form.question_type" placeholder="请选择试题类型">
                <el-option
                  v-for="item in questionsType"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="年级:" prop="grade_type">
              <el-select clearable filterable @change="changeGradeType" v-model="form.grade_type" placeholder="请选择年级">
                <el-option
                  v-for="item in changeGradeTypeList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="科目:" prop="subject_id">
              <el-select @change="changeSubject" clearable filterable v-model="form.subject_id" placeholder="请选择科目">
                <el-option
                  v-for="item in subjectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

           <el-col :span="12">
             <el-form-item label="知识点:" placeholder="请选择试题知识点" prop="language_points_id">
               <el-cascader
                 clearable
                 :options="formTreeLanguagePointsList"
                 v-model="form.languagePointsArrayId"
                 change-on-select>
               </el-cascader>
             </el-form-item>
           </el-col>

          <el-col :span="24">
            <el-form-item label="题目:">
              <script id="editor" ref="ueditor" type="text/plain">{{form.content}}</script>
            </el-form-item>
          </el-col>

           <el-col :span="24">
             <el-form-item label="总结升华:">
               <script id="summarizeEditor" ref="summarizeEditor" type="text/plain">{{form.summarize}}</script>
             </el-form-item>
           </el-col>

           <el-col :span="24">
             <el-form-item label="试题解析:">
               <script id="analysisEditor" ref="analysisEditor" type="text/plain">{{form.analysis}}</script>
             </el-form-item>
           </el-col>


           <el-col v-if="form.question_type == 3 || form.question_type == 4" :span="24">
             <el-form-item
               v-for="(option, index) in form.options"
               :label="'选项' + option.label"
               :key="index" >
               <el-input style="width: 200px;" v-model="option.option_name"></el-input>
               <el-button v-if="index != 0" type="danger" @click="deleteOption(index)">删除选项</el-button>
               <el-button v-else type="warning" @click="addOption()">添加选项</el-button>
             </el-form-item>
           </el-col>

           <el-col :span="24">
            <el-form-item label="答案:" prop="answer">
               <template>
                   <script id="answerEditor"  type="text/plain" ></script>
               </template>

              <template v-if="form.question_type && form.question_type !=2 && form.question_type != 6 && form.question_type != 7">
                <el-tag
                  v-for="tag in answerList"
                  style="margin-right: 5px;"
                  :key="tag"
                  @close="removeAnswer(tag)"
                  closable>
                  {{tag}}
                </el-tag>
                <input style="display: none;" type="text"/>
                <el-input
                  v-model="answer"
                  @keyup.enter.native="addAnswer()"
                  placeholder="每添加完一个答案请按回车键"
                  auto-complete="off">
                </el-input>
              </template>

              <template v-else-if="form.question_type == 6">
                <el-radio-group v-model="form.answer">
                  <el-radio :label="1">对</el-radio>
                  <el-radio :label="0">错</el-radio>
                </el-radio-group>
              </template>
            </el-form-item>
          </el-col>

           <el-col :span="24">
             <el-form-item label="讲解视频:">
               <el-upload
                   class="upload-demo"
                   :action="uploadAction"
                   multiple
                   :show-file-list="showFile"
                   :before-upload="beforeUploadVideo"
                   :on-success="uploadVideoSuccess"
                   :on-remove="removeVideo"
                   :before-remove="beforeRemoveVideo"
                   :file-list="form.videoList">
                   <el-button size="small" icon="el-icon-upload" type="primary">点击上传</el-button>
                   <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
               </el-upload>
             </el-form-item>
           </el-col>

          <el-col :span="24">
              <el-form-item>
                <el-button type="success" :disabled="uploadVideoRunning" v-if="form.id" @click="saveOrUpdateQuestions">修改</el-button>
                <el-button type="success" :disabled="uploadVideoRunning" v-else @click="saveOrUpdateQuestions">保 存</el-button>
              </el-form-item>
          </el-col>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
  import ueditor from 'ueditor'
  import { changeGradeTypeApi, getQuestionCategoryApi, changeSchoolTypeApi, getModeType } from '@/utils/education-api'
  import educationSearch from '@/components/education/education-search'
 // import choiceQuestion from '@/components/education/choice-question.vue'
  import { getSchoolTypeListApi, getQuestionTypeListApi,
      getGradeTypeListApi, getDictValueListByParentId } from '@/utils/system-dict-api'
  let thisPage = null
  export default {
    name: 'question',
    components: {educationSearch},
    data () {
      return {
        tableLoading: true,
        loading: true,
        headers: {
          token: localStorage.getItem('token')
        },
        uploadAction: this.$http.httpUrl('/upload/1'),
        uploadExcelAction: this.$http.httpUrl('/system/question/uploadExcel'),
        currentPage: 1,
        totalCount: 0,
        pageSize: 10,
        labelName: '添加试题',
        activeName: 'questions_list',
        answerList: [],
        showTableHeader: true,
        formTreeLanguagePointsList: [],
        answer: '',
        form: {
          languagePointsArrayId: [],
          language_points_id: '',
          analysis: '',
        //  category: '',
          grade_type: '',
          question_type: '',
          school_type: '',
          subject_id: '',
          content: '',
          answer: '',
          videoList: [],
          options: [],
          summarize: ''
        },
        modeTypeList: [],
        query: {
         // category: '',
          keyWord: '',
          subjectId: '',
          gradeType: '',
          schoolType: ''
        },
        uploadVideoRunning: false, // 是否正在上传教学视频
        questionsList: [],
        questionsType: [],
        showFile: true,
        gradeTypeList: [], // 年级列表
        schoolTypeList: [],  // 所属阶段列表

        subjectList: [],
        courseList: [],
        videoType: [
          'video/mp4',
          'video/mpeg4',
          'video/avi',
          'video/mpeg',
          'video/x-ms-wmv',
          'video/3gp'
        ],
        rules: {

          school_type: {
            required: true, message: '请选择阶段', trigger: 'blur'
          },

          question_type: {
            required: true, message: '请选择试题类型', trigger: 'blur'
          },

          grade_type: {
            required: true, message: '请选择年级', trigger: 'blur'
          },

          subject_id: {
            required: true, message: '请选择科目', trigger: 'blur'
          },

          language_points_id: {
            required: true, message: '请选择知识点', trigger: 'blur'
          }
        },
        changeGradeTypeList: [],
        parentCourseList: [],
        treeLanguagePointsList: [],
        editor: null,
       /* questionCategoryList: [
          {
            code: 1,
            value: '课程试题'
          },
          {
            code: 2,
            value: '试卷试题'
          }
        ],*/
        answerEditor: null,
        analysisEditor: null,
        summarizeEditor: null,
        config: {}
      }
    },

    beforeCreate () {
      thisPage = this
    },

    watch: {

      'form.school_type' (val) {
        let that = this
        let parentId = null
        for (let num in this.schoolTypeList) {
          if (this.schoolTypeList[num].code === val) {
            parentId = this.schoolTypeList[num].id
            break
          }
        }
        getDictValueListByParentId(parentId, 'grade_type', data => {
          that.changeGradeTypeList = data
        })
      },

      'form.grade_type' (val) {
        let that = this
        changeGradeTypeApi(val, function (data) {
          that.subjectList = data
        })
      },

      'form.subject_id' (val) {

      }
    },

    mounted () {
      let that = this
      ueditor.delEditor('editor') // 解决编辑器显示不出来，刷新一下就正常显示的问题
      ueditor.delEditor('answerEditor')
      ueditor.delEditor('analysisEditor')
      ueditor.delEditor('summarizeEditor')
      that.editor = ueditor.getEditor('editor', that.config)
      that.editor.offsetWidth = '100'
      that.answerEditor = ueditor.getEditor('answerEditor', that.config)
      that.answerEditor.offsetWidth = '100'
      that.analysisEditor = ueditor.getEditor('analysisEditor', that.config)
      that.analysisEditor.offsetWidth = '100'

      that.summarizeEditor = ueditor.getEditor('summarizeEditor', that.config)
      that.summarizeEditor.offsetWidth = '100'
      that.editor.addListener('ready', () => {
        that.editor.setShow(true)
      })

      getModeType(function (data) {
        that.modeTypeList = data
      })
      that.answerEditor.addListener('ready', () => {
        that.answerEditor.setShow(true)
      })

      that.analysisEditor.addListener('ready', () => {
        that.analysisEditor.setShow(true)
      })

      that.summarizeEditor.addListener('ready', () => {
        that.summarizeEditor.setShow(true)
      })

      that.getQuestionList()

      getSchoolTypeListApi(data => {
        that.schoolTypeList = data
      })

      getGradeTypeListApi(data => {
        that.gradeTypeList = data
        that.changeGradeTypeList = data
      })

      getQuestionTypeListApi(data => {
        that.questionsType = data
      })

    },

    methods: {

      // 试题预览
      lookQuestion (item) {
          this.$message.error('功能开发中, 敬请期待')
      },

      changeSubject (val) {
          this.axios.get(this.$http.httpUrl('/system/languagePoints'), {
              params: {
                  gradeType: this.form.grade_type,
                  subjectId: val,
                  lazy: 'false'
              }
          }).then(response => {
              this.formTreeLanguagePointsList = response.data.data.dataList
          })
      },


      searchQuestion (val) {
        this.query.subjectId = val.subjectId
        this.query.schoolType = val.schoolType
        this.query.gradeType = val.gradeType
        this.query.keyWord = val.keyWord
        this.currentPage = 1
        this.getQuestionList()
      },

      // 模板下载
      downTemplate () {
        let name = encodeURI('试题模板')
        location.href = this.$http.getFileHost() + '/excel/' + name + '.xlsx'
      },

      // 选中阶段
      changeSchoolType (val) {
        this.form.grade_type = ''
        this.form.languagePointsArrayId = []
        this.form.subject_id = ''
       /* if (that.form.grade_type) {
          that.form.grade_type = ''
        }*/
      },

      // 年级切换
      changeGradeType (val) {
        let that = this
        if (that.form.subject_id) {
          that.form.subject_id = ''
        }
      },

      // 选项
      deleteOption (index) { // 删除选项
        this.form.options.splice(index, 1)
      },

      uploadExcelSuccess (res, file) {
        this.loading.close()
        if (res.code === 1) {
          this.$message.success(res.message)
          this.getQuestionList()
        } else {
          this.$message.error(res.message)
        }
      },

      // 删除答案
      removeAnswer (tag) {
        let that = this
        that.$confirm('确定删除答案' + tag + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.answerList.splice(that.answerList.indexOf(tag), 1)
          that.message.success('答案' + tag + '删除成功')
        })
      },

      beforeUploadExcel (file) {
        this.loading = this.$loading({
          lock: true,
          text: '数据导入中, 请等待',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return true
      },

      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      changeQuestionType (val) {
        if (val === 2 || val === 7) {
          this.answerEditor.setShow(true)
          return
        } else if (val === 3 || val === 4) {
          this.form.options = []
          this.form.options.push({
            'label': 'A',
            'option_name': ''
          })
        }
        this.answerEditor.setHide(true)
      },
      // 添加选项
      addOption () {
        let label = String.fromCharCode('A'.charCodeAt() + this.form.options.length) // 动态生成A B C D
        this.form.options.push({
          label: label,
          option_name: ''
        })
      },

      addAnswer () {
        if (this.answer) {
          let message = ''
          if (this.answerList && this.answerList.indexOf(this.answer) >= 0) {
            message = '已经有这个答案了'
          }
          if (message) {
            this.$message({
              type: 'warning',
              message: message
            })
          } else {
            if (!this.answerList) {
              this.answerList = []
            }
            this.answerList.push(this.answer)
            this.answer = ''
          }
        }
      },
      beforeUploadVideo (file) {
        if (this.videoType.indexOf(file.type) === -1) {
          this.showFile = false
          this.$message.error('视频格式错误')
          return false
        } else if (this.form.videoList.length > 1) {
          this.$message.error('您只能上传一个视频')
          return false
        } else {
          this.uploadVideoRunning = true
          this.showFile = true
        }
        return true
      },

      // 视频上传成功回调
      uploadVideoSuccess (res, file) {
        this.uploadVideoRunning = false
        if (res.code === 1) {
          this.$message.success(res.message)
          this.form.videoList.push({
            url: res.url,
            name: file.name
          })
        } else {
          this.$message.error(res.message)
          return false
        }
      },
      // 删除视频
      removeVideo (file) {
        let index = this.form.videoList.indexOf(file.url)
        this.form.videoList.splice(index, 1)
      },

      beforeRemoveVideo (file, fileList) {
        let name = file.name
        return this.$confirm('确定移除讲解视频' + name + '?')
      },

      handleSizeChange (val) {
        this.pageSize = val
        this.currentPage = 1
        this.getQuestionList()
      },

      handleCurrentChange (val) {
        this.tableLoading = true
        this.currentPage = val
        this.getQuestionList()
      },

      updateQuestions (item) {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/question/findById'), {
            params: {
                id: item.id
            }
        }).then(response => {
            let result = response.data.data
            that.form.languagePointsArrayId = result.languagePointsIds
            that.formTreeLanguagePointsList = result.languagePointsList
            that.subjectList = result.subjectList
            that.form.school_type = item.school_type
            that.form.grade_type = item.grade_type
            that.activeName = 'questions_form'
            that.labelName = '修改试题'
            let videoNewList = []
            that.form.answer = item.answer
            that.form.summarize = item.summarize
            that.editor.setContent(item.content)
            if (item.analysis) {
                that.analysisEditor.setContent(item.analysis)
            }
            if (item.summarize) {
                that.summarizeEditor.setContent(item.summarize)
            }
            // 获取试题类型
            if (item.question_type === 2 || item.question_type === 7) {
                that.answerEditor.setContent(item.answer)
            } else {
                that.answerEditor.setHide(true)
                if (item.question_type === 3 || item.question_type === 4) {
                    that.answerEditor.setHide(false)
                    if (item.options) {
                        let options = item.options.split(',')
                        that.form.options = []
                        for (let i = 0; i < options.length; i++) {
                            let label = String.fromCharCode('A'.charCodeAt() + i)
                            if (options[i]) {
                                that.form.options.push({
                                    'label': label,
                                    'option_name': options[i]
                                })
                            }
                        }
                    }
                    that.parserAnswer(item.answer, that)
                } else if (item.question_type === 6) { // 选择题
                    that.answerEditor.setHide(false)
                    that.form.answer = parseInt(item.answer) // 注: 组件不支持数字字符串绑定
                } else {
                    that.answerEditor.setHide(false) // 百度编辑器设置隐藏
                    that.parserAnswer(item.answer, that)
                }
            }

            if (item.video_url) {
                item.video_url.split(',').forEach(function (item) {
                    if (item !== '') {
                        let index = item.lastIndexOf('/')
                        let fileName = item.substr(index + 1, item.length)
                        videoNewList.push({
                            'name': fileName,
                            'url': item
                            //  'url': that.$http.getHost() + item
                        })
                    }
                })
            }
            this.form.id = item.id
            // this.form.mode_type = item.mode_type
            this.form.videoList = videoNewList
            this.form.content = item.content
            this.form.school_type = item.school_type
            this.form.grade_type = item.grade_type
            this.form.question_type = item.question_type
            this.form.subject_id = item.subject_id
           // this.form.category = item.category
        })

      },

      getLanguagePointsParentId (that, val) {
          if (!val) {
              that.form.languagePointsArrayId = []
          } else {
              that.axios.get(that.$http.httpUrl('/system/languagePoints/getParentId'), {
                  params: {
                      languagePointsId: val
                  }
              }).then(response => {
                  that.form.languagePointsArrayId = response.data.data
              })
          }
      },

      parserAnswer (answer, that) {
        if (answer) {
          if (answer.indexOf(',') !== -1) {
            let answerArray = answer.split(',')
            answerArray.forEach(function (value) {
              if (value) {
                that.answerList.push(value)
              }
            })
            // that.answerList = item.answer.substr(0, item.answer.length - 1).split(',')
          } else {
            that.answerList.push(answer)
          }
        }
      },
      // 试题列表
      getQuestionList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/question'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            keyWord: that.query.keyWord,
            languagePointsId: that.query.languagePointsId,
          //  category: that.query.category,
            subjectId: that.query.subjectId,
            gradeType: that.query.gradeType,
            schoolType: that.query.schoolType
          }
        }).then(function (response) {
          that.tableLoading = false
          that.questionsList = response.data.data.dataList
          that.totalCount = response.data.data.total
        }).catch(function (error) {
          console.log(error)
        })
      },
      getGradeTypeList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            type: 'grade_type'
          }
        }).then(function (response) {
          that.gradeTypeList = response.data.data.dataList
          that.changeGradeTypeList = response.data.data.dataList
        }).catch(function (error) {
          console.log(error)
        })
      },

      handleClick (tab) {
        let selectTab = tab.name
        let that = this
        if (selectTab === 'questions_list') {
          that.labelName = '添加试题'
        }
        that.clearForm(that)
      },

      deleteById (item) {
        let that = this
        that.$confirm('此操作将删除试题及其关联数据？删除后将不可恢复,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/question'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getQuestionList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },

      saveOrUpdateQuestions () {
        let that = this
        if (that.form.languagePointsArrayId.length > 0) {
            let length = that.form.languagePointsArrayId.length
            that.form.language_points_id =  that.form.languagePointsArrayId[length - 1]
        }
        delete (that.form.languagePointsArrayId)
        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {

            let content = that.getUeditorContent()

            if (!content) {
              that.$message.error('请输入试题内容')
              return
            }

            let analysisContent = that.getAnalysisContent()
            /* if (!analysisContent) {
              that.$message.error('请输入试题解析内容')
              return
            } */
            that.form.content = content
            that.form.analysis = analysisContent
            that.form.summarize = that.getSummarizeContent()
            switch (that.form.question_type) {
              case 2:
              case 7:
                that.form.answer = that.getAnswerContent()
                break
              default:
                if (that.answerList.length > 0) {
                  that.form.answer = ''
                  for (let i = 0; i < that.answerList.length; i++) {
                    that.form.answer += that.answerList[i] + ','
                  }
                }
                break
            }

            if (typeof that.form.answer !== 'number') {
              if (!that.form.answer) {
                that.$message.error('请输入答案')
                return
              }
            }

            // 视频
            if (that.form.videoList) {
              let video = ''
              that.form.videoList.forEach(function (item) {
                video += item.url + ','
              })
              that.form.video_url = video
            }
            delete (that.form.videoList)
            that.save(that, null)
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },

      save (that, type) {
        let params = this.form
        that.axios.post(that.$http.httpUrl('/system/question'), params).then(function (response) {
          if (response.data.code === 1) {
            if (!that.form.id) {
              that.$confirm(response.data.message + ',是否继续添加?', '提示', {
                confirmButtonText: '继续添加',
                cancelButtonText: '返回列表',
                type: 'warning'
              }).then(() => {
                that.clearForm(that)
              }).catch(() => {
                that.activeName = 'questions_list'
                that.labelName = '添加试题'
                that.clearForm(that)
                that.getQuestionList()
              })
            } else {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              setTimeout(function () {
                that.activeName = 'questions_list'
                that.labelName = '添加试题'
                that.clearForm(that)
                that.getQuestionList()
              }, 1000)
            }
          } else {
            that.$message({
              type: 'error',
              message: response.data.message
            })
          }
        }).catch(function (error) {
          console.log(error)
        })
      },

      clearForm (that) {
        that.editor.setShow(true)
        that.editor.setContent('')
        that.answerEditor.setShow(true)
        that.answerEditor.setContent('')
        that.summarizeEditor.setShow(true)
        that.summarizeEditor.setContent('')
        that.analysisEditor.setShow(true)
        that.analysisEditor.setContent('')
        that.answerList = []
        that.form = {
          grade_type: '',
          languagePointsArrayId: [],
          language_points_id: '',
          question_type: '',
          school_type: '',
          subject_id: '',
          content: '',
          summarize: '',
          analysis: '',
          answer: '',
          videoList: [],
          options: []
        }
      },


      getQuestionType () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            type: 'question_type'
          }
        }).then(function (response) {
          that.questionsType = response.data.data.dataList
        }).catch(function (error) {
          console.log(error)
        })
      },

      getSchoolType () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            type: 'school_type'
          }
        }).then(function (response) {
          that.schoolTypeList = response.data.data.dataList
        }).catch(function (error) {
          console.log(error)
        })
      },

      // 获取文档内容
      getUeditorContent () {
        return this.editor.getContent()
      },

      // 获取试题解析内容
      getAnalysisContent () {
        return this.analysisEditor.getContent()
      },

      getAnswerContent () {
        return this.answerEditor.getContent()
      },

      getSummarizeContent () {
        return this.summarizeEditor.getContent()
      }
    },

    filters: {
      getGradeName (gradeType) {
        for (let i = 0; i < thisPage.gradeTypeList.length; i++) {
          if (thisPage.gradeTypeList[i].code === gradeType) {
            return thisPage.gradeTypeList[i].value
          }
        }
        return '无'
      },

   /*   getQuestionCategory (val) {
        for (let i = 0; i < thisPage.entranceQuestionType.length; i++) {
          if (thisPage.entranceQuestionType[i].code === val) {
            return thisPage.entranceQuestionType[i].value
          }
        }
      },*/

      getQuestionTypeName (questionType) {
        for (let i = 0; i < thisPage.questionsType.length; i++) {
          if (thisPage.questionsType[i].code === questionType) {
            return thisPage.questionsType[i].value
          }
        }
        return '无'
      }
    }
  }
</script>
<style lang="scss">
  .edui-default .edui-editor-toolbarbox {
    position: relative !important;
  }

  .mod-demo-ueditor {
    position: relative;
    z-index: 510;
    > .el-alert {
      margin-bottom: 10px;
    }
  }
</style>
